package com.css.zfzx.sjcj.modules.hddcB6_GeocheSvyDataTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.superRepository.SuperRepository;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB5_GeophySvyDataTable.repository.entity.HddcB5GeophysvydatatableEntity;
import com.css.zfzx.sjcj.modules.hddcB6_GeocheSvyDataTable.repository.HddcB6GeochesvydatatableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB6_GeocheSvyDataTable.repository.HddcB6GeochesvydatatableRepository;
import com.css.zfzx.sjcj.modules.hddcB6_GeocheSvyDataTable.repository.entity.HddcB6GeochesvydatatableEntity;
import com.css.zfzx.sjcj.modules.hddcB6_GeocheSvyDataTable.service.HddcB6GeochesvydatatableService;
import com.css.zfzx.sjcj.modules.hddcB6_GeocheSvyDataTable.viewobjects.HddcB6GeochesvydatatableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB6_GeocheSvyDataTable.viewobjects.HddcB6GeochesvydatatableVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.modules.hddcGeochemicalSvyLine.repository.entity.HddcGeochemicalsvylineEntity;
import com.css.zfzx.sjcj.modules.hddcGeochemicalSvyLine.service.HddcGeochemicalsvylineService;
import com.css.zfzx.sjcj.modules.hddcGeochemicalSvyPoint.repository.entity.HddcGeochemicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeochemicalSvyPoint.service.HddcGeochemicalsvypointService;
import com.css.zfzx.sjcj.modules.hddcGeophySvyLine.repository.entity.HddcGeophysvylineEntity;
import com.css.zfzx.sjcj.modules.hddcGeophySvyPoint.repository.entity.HddcGeophysvypointEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangcong
 * @date 2020-11-27
 */
@Service
public class HddcB6GeochesvydatatableServiceImpl implements HddcB6GeochesvydatatableService {

	@Autowired
    private HddcB6GeochesvydatatableRepository hddcB6GeochesvydatatableRepository;
    @Autowired
    private HddcB6GeochesvydatatableNativeRepository hddcB6GeochesvydatatableNativeRepository;
    @Autowired
    private HddcGeochemicalsvypointService hddcGeochemicalsvypointService;
    @Autowired
    private HddcGeochemicalsvylineService hddcGeochemicalsvyLineService;

    @Override
    public JSONObject queryHddcB6Geochesvydatatables(HddcB6GeochesvydatatableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB6GeochesvydatatableEntity> hddcB6GeochesvydatatablePage = this.hddcB6GeochesvydatatableNativeRepository.queryHddcB6Geochesvydatatables(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcB6GeochesvydatatablePage);
        return jsonObject;
    }


    @Override
    public HddcB6GeochesvydatatableEntity getHddcB6Geochesvydatatable(String id) {
        HddcB6GeochesvydatatableEntity hddcB6Geochesvydatatable =
                this.hddcB6GeochesvydatatableRepository.findByUuidAndIsValid(id,"1");
         return hddcB6Geochesvydatatable;
    }
    @Override
    public HddcB6GeochesvydatatableEntity findBySvypointid(String svypointid){
        return hddcB6GeochesvydatatableRepository.findBySvypointidAndIsValid(svypointid,"1");
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB6GeochesvydatatableEntity saveHddcB6Geochesvydatatable(HddcB6GeochesvydatatableEntity hddcB6Geochesvydatatable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB6Geochesvydatatable.setUuid(uuid);
        hddcB6Geochesvydatatable.setCreateUser(PlatformSessionUtils.getUserId());
        hddcB6Geochesvydatatable.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcB6Geochesvydatatable.setIsValid("1");
        this.hddcB6GeochesvydatatableRepository.save(hddcB6Geochesvydatatable);
        return hddcB6Geochesvydatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB6GeochesvydatatableEntity updateHddcB6Geochesvydatatable(HddcB6GeochesvydatatableEntity hddcB6Geochesvydatatable) {
        UpdateUtil.copyNullProperties(hddcB6GeochesvydatatableRepository.findByUuidAndIsValid(hddcB6Geochesvydatatable.getUuid(), "1"), hddcB6Geochesvydatatable);
        hddcB6Geochesvydatatable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB6Geochesvydatatable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB6GeochesvydatatableRepository.save(hddcB6Geochesvydatatable);
        return hddcB6Geochesvydatatable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB6Geochesvydatatables(List<String> ids) {
        List<HddcB6GeochesvydatatableEntity> hddcB6GeochesvydatatableList = this.hddcB6GeochesvydatatableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB6GeochesvydatatableList) && hddcB6GeochesvydatatableList.size() > 0) {
            for(HddcB6GeochesvydatatableEntity hddcB6Geochesvydatatable : hddcB6GeochesvydatatableList) {
//                this.hddcB6GeochesvydatatableRepository.delete(hddcB6Geochesvydatatable);
                hddcB6Geochesvydatatable.setIsValid("0");
                hddcB6Geochesvydatatable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB6Geochesvydatatable.setUpdateTime(new Date());
                this.hddcB6GeochesvydatatableRepository.save(hddcB6Geochesvydatatable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcB6GeochesvydatatableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB6GeochesvydatatableEntity> yhDisasterEntities = hddcB6GeochesvydatatableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB6GeochesvydatatableVO> list=new ArrayList<>();
        for (HddcB6GeochesvydatatableEntity entity:yhDisasterEntities) {
            HddcB6GeochesvydatatableVO yhDisasterVO=new HddcB6GeochesvydatatableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地球化学探测数据表", "地球化学探测数据表", HddcB6GeochesvydatatableVO.class, "地球化学探测数据表.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcB6GeochesvydatatableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB6GeochesvydatatableVO.class, params);
            List<HddcB6GeochesvydatatableVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcB6GeochesvydatatableVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcB6GeochesvydatatableVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    @Autowired
    SuperRepository superRepository;
    @Transactional
    @Override
    public int dataQualityCheck() {
        List<HddcB6GeochesvydatatableEntity> updateList =new ArrayList<>();
        List<HddcB6GeochesvydatatableEntity> listAll = hddcB6GeochesvydatatableRepository.findByAll();
        for (HddcB6GeochesvydatatableEntity b2All: listAll) {
            String str="";
            if(StringUtils.isEmpty(b2All.getSvypointid())){
                str += "【地球化学探测数据表】测点编号为空。";
            }else {
                HddcGeochemicalsvypointEntity hddcGeochemicalsvypointEntity = hddcGeochemicalsvypointService.findById(b2All.getSvypointid());
                if (hddcGeochemicalsvypointEntity == null) {
                    str += "【地球化学探测测点】表单中的测点编号与【地球化学探测数据表】中的测点编号不一致。";
                }else {
                    if (StringUtils.isEmpty(b2All.getSvylineid())) {
                        str += "【地球化学探测数据表】测线编号为空。";
                    } else {
                        if (!b2All.getSvylineid().equals(hddcGeochemicalsvypointEntity.getSvylineid())) {
                            str += "【地球化学探测测点】表单中的测线编号与【地球化学探测数据表】中的测线编号不一致。";
                        }
                    }
                    if (StringUtils.isEmpty(b2All.getSvymethod()) || "null".equals(b2All.getSvymethod())) {
                        str += "【地球化学探测数据表】探测方法为空。";
                    } else {
                        if (!b2All.getSvymethod().equals(hddcGeochemicalsvypointEntity.getSvymethod())) {
                            str += "【地球化学探测测点】表单中的探测方法与【地球化学探测数据表】中的探测方法不一致。";
                        }
                    }
                }
            }
            if (str.isEmpty()) {
                str += "【地球化学探测测点】与【地球化学探测数据表】质检成功。";
                b2All.setQualityinspectionStatus("1");
            }else {
                b2All.setQualityinspectionStatus("2");
            }
            String[] split = str.split("。");
            for (int i = 0; i < split.length; i++) {
                if (i==0){
                    b2All.setExtends1(split[i]);
                }else if(i==1) {
                    b2All.setExtends2(split[i]);
                }else if(i==2) {
                    b2All.setExtends3(split[i]);
                }
            }
            updateList.add(b2All);
        }
        superRepository.batchUpdate(updateList);
        return 1;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcB6GeochesvydatatableVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcB6GeochesvydatatableEntity yhDisasterEntity = new HddcB6GeochesvydatatableEntity();
            HddcB6GeochesvydatatableVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcB6Geochesvydatatable(yhDisasterEntity);
        }
    }
}


